# -*- coding: utf-8 -*-
import xlrd
import xlwt
from datetime import datetime


def open_excel(file='./BasicInfo.xlsx'):
    try:
        data = xlrd.open_workbook(file)
        return data
    except Exception, e:
        print str(e)


def get_bussiness(data):
    ''''''
    Bsns = {}
    table0 = data.sheets()[0]
    nrows = table0.nrows
    for rownum in range(1, nrows):
        if table0.row_values(rownum)[0] in Bsns:
            routeset = set(table0.row_values(rownum)[1:])
            # print table0.row_values(rownum)[1:]
            if '' in routeset:
                routeset.remove('')
            Bsns[table0.row_values(rownum)[0]].append(routeset)
        else:
            routesetlist = []
            routeset = set(table0.row_values(rownum)[1:])
            if '' in routeset:
                routeset.remove('')
            routesetlist.append(routeset)
            Bsns[table0.row_values(rownum)[0]] = routesetlist
    # print Bsns
    return Bsns


def get_overhaul(data):
    table0 = data.sheets()[0]
    access_portlist = table0.row_values(0)[0:]
    # print access_portlist
    access_portset = set(access_portlist)
    if '' in access_portset:
        access_portset.remove('')
    # print access_portset
    portlist = []
    nrows = table0.nrows
    for rownum in range(1, nrows):
        # print table0.row_values(rownum)[1:]
        portlist = portlist + table0.row_values(rownum)[1:]
    # print len(portlist)
    # print portlist
    portset = set(portlist)
    # print portset
    # print len(portset)
    if '' in portset:
        portset.remove('')
    # print portset
    # print len(portset)
    # print 'portset'
    # print portset
    assemble_ports = []

    for possible_port in portset:
        # print(set([possible_port,]))
        combination = []
        combination.append(access_portset | set([possible_port, ]))
        combination.append(possible_port)
        assemble_ports.append(combination)
    # print 'assemble_port:'
    # for p in assemble_ports:
    #   print p
    # print len(assemble_ports)
    return assemble_ports


def write_excel(wdata):

    book = xlwt.Workbook()
    sheetname = 'result of '
    sheet1 = book.add_sheet(sheetname)
    for i in range(0, len(wdata)):
                # print wdata[i]
                # print wdata[i][0]
        str = ''
        for P in wdata[i][0]:
            str = str + P + '_'
        wdata[i][0] = str
        # print wdata[i][0]
    for i in range(0, len(wdata)):
        for j in range(0, len(wdata[i])):
            sheet1.row(i).write(j, wdata[i][j])
    resultxlsxname = 'result ' + datetime.now().__str__()
    resultxlsxname = resultxlsxname.replace(' ', '_')
    resultxlsxname = resultxlsxname.replace('.', '_')
    resultxlsxname = resultxlsxname.replace(':', '')
    resultxlsxname = resultxlsxname.replace('-', '')
    resultxlsxname = resultxlsxname + '.xlsx'
    print resultxlsxname
    book.save(resultxlsxname)


def main():
    data = open_excel()
    print data
    data_write = []
    
    # dic key is yewu value is list contain baohu
    bussinesslist = get_bussiness(data)
    # print bussinesslist
    # contain another port possible unaviable
    unaviable_portlist = get_overhaul(data)
    for bn, routelist in bussinesslist.iteritems():
        if len(routelist) < 2:
            row_wr = []
            row_wr.append(bn)
            row_wr.append(len(routelist))
            data_write.append(row_wr)
            print bn
            print len(routelist)


    # print(len(unaviable_portlist))
    # for unPort in unaviable_portlist:
    #     affectB = unPort
    # print unPort
    #     for bn, routelist in bussinesslist.iteritems():
    # print bn
    # print len(routelist)
    #         if (unPort[0] & routelist[0]) and (unPort[0] & routelist[1]):
    #             affectB.append(bn)
    #     if len(affectB) > 2:
    #         data_write.append(affectB)
    # for i in data_write:
    # print i
    write_excel(data_write)


if __name__ == '__main__':
    main()
